import { alert } from "./alert.js";
import { format } from './timeago.js';

const toast = (title, state=false) => {
	uni.showToast({
		title,
		icon: state? "success": "none",
	})
}

const verifyPhone = (phone)=> {
	let myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
	if (phone.length < 11) {
		toast('手机号码最短需要 11 个位')
		return false
	} else {
		if (!myreg.test(phone)) {
			toast('手机号格式有误！')
			return false
		}
	}
	return true
}

const verifyIdentity = (identity) => {
	let reg =  (/^[1-9]{1}[0-9]{14}$|^[1-9]{1}[0-9]{16}([0-9]|[xX])$/)
	if(!reg.test(identity)) {
		toast('身份证格式有误！')
		return false
	} else {
		return true
	}
}


const iosTextareaFn = (that) =>{
  let platform = uni.getSystemInfoSync().platform
  if (platform == 'ios') {
	  that.iosTextareaClass = 'margin-top: -15upx;margin-left: -10upx;'
  }
}

const getMap = ()=> {
	return new Promise((resolve, reject) => {
		uni.getLocation({
			type: 'wgs84',
			success: ({longitude, latitude}) => {
				uni.setStorageSync('userCoordinate', {longitude, latitude})
				resolve()
			},
			fail: () => {
				reject()
			}
		})
	})
}

const ConversionMap = (num) => {
	let distance = parseInt(num)
	return distance < 1000? distance+"m" : (Math.round(distance/100)/10).toFixed(1) + "km"
}

//时分秒转换
const transitionTime = (dates)=> {
	let date = new Date(dates * 1000)
	var year = date.getFullYear()
	var month = date.getMonth() + 1
	var day = date.getDate()
	var hour = date.getHours()
	var minute = date.getMinutes()
	var second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
} 


const formatNumber =(n)=> {  
  n = n.toString()  
  return n[1] ? n : '0' + n  
}   

const timeFormat = (time) =>{
  return format(time * 1000, 'zh_CN')
}

const countTime = (endDate) => {
  let date = new Date()
  let now = date.getTime()
  var end = endDate
  var leftTime = end - now // 时间差
  var d, h, m, s, ms
  if (leftTime >= 0) {
    // d = Math.floor(leftTime / 1000 / 60 / 60 / 24)
    h = Math.floor(leftTime / 1000 / 60 / 60)
    m = Math.floor(leftTime / 1000 / 60 % 60)
    s = Math.floor(leftTime / 1000 % 60)
    ms = Math.floor(leftTime % 1000)
    if (ms < 100) {
      ms = '0' + ms
    }
    if (s < 10) {
      s = '0' + s
    }
    if (m < 10) {
      m = '0' + m
    }
    if (h < 10) {
      h = '0' + h
    }
    return {
      // d: parseInt(d),
      h: parseInt(h),
      m,
      s,
      state: false
    }
  } else {
    console.log('已截止')
    return {
      // d: '00',
      h: '00',
      m: '00',
      s: '00',
      state: true
    }
  }
}

module.exports = {
	verifyPhone,
	toast,
	iosTextareaFn,
	alert,
	getMap,
	ConversionMap,
	transitionTime,
	timeFormat,
	verifyIdentity,
	countTime
}